package net.alan.modules.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.alan.common.utils.Base64;
import net.alan.common.utils.IOUtils;
import net.alan.common.utils.MD5Util;
import net.alan.common.utils.StringUtils;
import net.alan.modules.aspect.AdminRole;
import net.alan.modules.aspect.NotAuthorize;
import net.alan.modules.bean.*;
import net.alan.modules.cache.WebContextUtil;
import net.alan.modules.echart.EchartsUtils;
import net.alan.modules.service.IEmailService;
import net.alan.modules.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Api(tags = "用户管理")
@Controller
@RequestMapping(value = "user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;
    @Resource
    private IEmailService emailService;
    @Autowired
    private CustomConfig customConfig;

    /**
     * 邮件发送
     */
    @NotAuthorize
    @ApiOperation(value = "找回密码", notes = "")
    @RequestMapping(value = "sendmail", method = RequestMethod.POST)
    @ResponseBody
    public Result findpass(String email) throws Exception {
        String url = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + request.getContextPath();
        return emailService.sendSimpleMail(email, url, session.getId());
    }

    @NotAuthorize
    @ApiOperation(value = "重置找回密码", notes = "")
    @RequestMapping(value = "resetpass", method = RequestMethod.POST)
    @ResponseBody
    public Result resetpass(String code, String sessionId, String password) throws Exception {
        if (!session.getId().equals(sessionId)) {
            return ResultUtil.error("会话过期，请重新尝试!");
        }
        String email = Base64.decodeString(code);
        return this.userService.resetPass(email, password);
    }

    @NotAuthorize
    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ResponseBody
    public Result register(User user) throws Exception {
        user.setPassword(MD5Util.md5(user.getPassword()));
        return userService.addUser(user);
    }

    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "editpass", method = RequestMethod.POST)
    @ResponseBody
    public Result editpass(String oldpassword, String password) throws Exception {
        return userService.editPass(oldpassword, password);
    }

    @ApiOperation(value = "修改信息")
    @RequestMapping(value = "editinfo", method = RequestMethod.POST)
    @ResponseBody
    public Result editinfo(User user) throws Exception {
        return userService.editUser(user);
    }

    @AdminRole
    @ApiOperation(value = "修改群数量")
    @RequestMapping(value = "editmax", method = RequestMethod.POST)
    @ResponseBody
    public Result editmax(Integer id, Integer maxProject) throws Exception {
        return userService.editMaxProject(id, maxProject);
    }

    @ApiOperation(value = "获取一个用户")
    @ApiImplicitParam(name = "id", value = "userId", required = true, dataType = "Integer")
    @RequestMapping(value = "get/{id}", method = RequestMethod.GET)
    @ResponseBody
    public User get(@PathVariable("id") Integer id) throws Exception {
        if (id == null || id == 0)
            id = WebContextUtil.getUserId();
        User user = userService.getById(User.class, id);
        return user.copy();
    }

    @ApiOperation(value = "用户日志列表")
    @RequestMapping(value = "listlog", method = RequestMethod.GET)
    @ResponseBody
    public PageModel listlog(PageModel pageModel) throws Exception {
        Page page = userService.findUserLogByUserId(WebContextUtil.getUserId(), pageModel);
        return pageModel.toPageModel(page);
    }

    @AdminRole
    @ApiOperation(value = "所有用户")
    @RequestMapping(value = "userall", method = RequestMethod.GET)
    @ResponseBody
    public PageModel userAll(PageModel pageModel) throws Exception {
        Page page = null;
        if (StringUtils.isNoneBlank(pageModel.getSearch())) {
            page = userService.findByAccountOrName(pageModel.getSearch(), pageModel);
        } else {
            page = userService.findAll(User.class, pageModel);
        }
        return pageModel.toPageModel(page);
    }

    @AdminRole
    @ApiOperation(value = "用户活跃数据", notes = "用于绘图使用")
    @RequestMapping(value = "useractive", method = RequestMethod.POST)
    @ResponseBody
    public String getUserActive(PageModel pageModel) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("id", "custom");
        dataMap.put("title", "用户活跃度");
        pageModel.setPage(1);
        pageModel.setLimit(10);
        Page<UserStat> page = this.userService.findUserStat(pageModel);
        List<UserStat> list = page.getContent();
        if (list != null) {
            Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
            for (UserStat userstat : list) {
                map.put(userstat.getDay(), userstat.getUsers());
            }
            dataMap.put("xdata", StringUtils.join(map.keySet()));
            dataMap.put("data", StringUtils.join(map.values()));
        }

        return EchartsUtils.buildEcharts("line.txt", dataMap);
    }

    /**
     * 图片上传
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public Result doUploadFile(HttpServletRequest request)
            throws Exception, IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        try {
            String filePath = WebContextUtil.getUserId() + ".jpg";
            IOUtils.copyStream(file.getInputStream(), customConfig.getPhotoPath() + filePath);
        } catch (Exception baseExecption) {
            baseExecption.printStackTrace();
        }
        return ResultUtil.success();
    }

}
